from contextlib import asynccontextmanager

from fastapi import FastAPI

from app.core.log_config import setup_logging
from app.core.scheduler_tasks import setup_daily_reset_scheduler, scheduler
from app.core.parse_openapi_docs import parse_openapi_docs
from app.db.cache_factory import CacheFactory
from app.db.seed_data import async_init_seed_data
from app.db.session_factory import get_async_context_manager, DatabaseFactory


# 生命周期管理器
@asynccontextmanager
async def lifespan(app: FastAPI):
    await startup(app)
    yield
    await shutdown(app)


async def startup(app: FastAPI):
    print("{0:-^100}".format(f"应用程序已启动"))

    setup_logging()
    # 每次启动，解析 openapi 文档，将 api 接口保存至本地 api.json，用于 api 接口数据初始化或者同步
    await parse_openapi_docs(app)

    # 启动时初始化数据库
    await DatabaseFactory().init_db()

    # 插入种子数据
    async with get_async_context_manager() as session:
        await async_init_seed_data(session=session)

    # 启动定时任务
    setup_daily_reset_scheduler()
    scheduler.start()
    print("{0:-^100}".format("定时任务调度器已启动"))

async def shutdown(app: FastAPI):
    # 优雅关闭定时任务
    if scheduler.running:
        scheduler.shutdown()
        print("{0:-^100}".format("定时任务调度器已停止"))

    await DatabaseFactory().close()
    await CacheFactory().close()
    print("{0:-^100}".format(f"应用程序已停止"))